package ms.platform.progress.controller;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import ms.platform.plan.dto.ModelDto;
import ms.platform.plan.dto.TargetDto;
import ms.platform.plan.model.ModelPlan;
import ms.platform.plan.model.ModelProcessPlan;
import ms.platform.plan.service.BusModelService;
import ms.platform.progress.dao.FactoryPlanDao;
import ms.platform.progress.dto.AnnexDto;
import ms.platform.progress.dto.MeterUsedDto;
import ms.platform.progress.dto.ProgressDetailDto;
import ms.platform.progress.dto.ProgressDto;
import ms.platform.progress.service.FactoryPlanService;
import ms.platform.progress.service.IndexAuditService;
import ms.platform.system.controller.BaseController;
import ms.platform.util.*;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/bus/progress/")
public class FactoryPlanController extends BaseController{
	@Autowired
	FactoryPlanService factoryService;
	@Autowired
	BusModelService busModelService;
	@Autowired
	FactoryPlanDao factoryPlanDao;
	@Autowired
	IndexAuditService indexAuditService;
	/**
	 * 我的计划列表
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/myPlan")
	public String meterList(@RequestParam Map<String,Object> map, HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		//总条数
		map.put("userId", userId);
		map.put("count", factoryService.queryPageBusModelPlanCount(map));
		List<ModelDto> list = factoryService.queryPageBusModelPlanList(PageUtils.Page(request,map));
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String newDate = df.format(new Date());
		for (ModelDto busModel : list) {
			if (!StringUtil.isNullOrBlock(busModel.getLastReportTime())) {
				if (DateUtil.middate(newDate, busModel.getLastReportTime(), df) == 0 && busModel.getSubmitFlagText().equals("已提交")) {
					busModel.setLastReportTimeText("已提交");
				} else if(DateUtil.middate(newDate, busModel.getLastReportTime(), df) == 0 && busModel.getSubmitFlagText().equals("已保存")) {
					busModel.setLastReportTimeText("已保存");
				}else{
					busModel.setLastReportTimeText("未提交");
				}
			} else {
				busModel.setLastReportTimeText("未提交");
			}
		}
		List<TargetDto> mTypeList = busModelService.queryAllmodelType();
		request.setAttribute("mTypeList",mTypeList);
		request.setAttribute("list", list);
		PageUtils.calculate(map);
		request.getSession().setAttribute("queryPageBusModelPlan", map);
		return "progress/myPlan";
	}

	/**
	 * 跳转到新增进度页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addProgress")
	public Object toAddProgress(@RequestParam Map<String,String> param,HttpServletRequest request){
		Integer id = Integer.parseInt(param.get("mapId"));
		request.setAttribute("map", param);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("modelPlanId", id);
		map.put("recordDate", DateUtil.getDateString(new Date(), "yyyy-MM-dd"));
		int modelPlanId = (Integer) map.get("modelPlanId");//拿到planid
		ModelPlan modelPlan = factoryService.getmodelPlan(modelPlanId);//获取结束时间
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String endDate = df.format(modelPlan.getPlanEndTime());
		String newDate = df.format(new Date());
		//判断当前时间是否大于计划结束时间
		//如果大于，则沿用计划结束最后天来提交进度
		Date start = new Date();
		boolean endtime = false;
		if (DateUtil.middate(newDate, endDate, df) > 0) {
			start.setTime( modelPlan.getPlanEndTime().getTime());//重新赋值 减去1天
			endDate = df.format(start);
			map.put("recordDate",endDate);
			endtime = true;
		}
		ProgressDto dto = factoryService.queryProcessRecordByPlanIdAndReportTime(map);

		if(null != dto){
			ProgressDetailDto detailDto = factoryService.getProgressDetailById(dto.getId(), false, endtime, false);
			//计划时间结束 计算计划总耗时
			if (endtime) {
				detailDto.setDifferTime(DateUtil.middate(newDate, df.format(modelPlan.getPlanEndTime()), df).intValue());
				detailDto.setPlanTotalTime(1);
				//计算延期天数
				List<ModelProcessPlan> processList = factoryPlanDao.queryModelProcessByPlanId(id);
				Date update = new Date();//取上一个时间
				Date todydate = new Date();//当前结束时间
				for (ModelProcessPlan plan : processList) {
					todydate = plan.getPlanEndTime();//得到当前结束时间
					if (dto.getPlanProcessName().equals(plan.getProcessName())) {
						break;//如果相等,结束,取上一个时间
					}
					update = plan.getPlanEndTime();
				}
				//上一个进度结束时间

				//延期天数=(当前进度结束时间-上一个进度结束时间)*(1-实际完成比例)+当天-当前进度结束时间
				String tody = df.format(todydate);
				String updt = df.format(update);
				//当前进度结束时间-上一个进度结束时间
				int nwdate = DateUtil.middate(tody, updt, df).intValue();
				//当天-当前进度结束时间
				int todaydate = DateUtil.middate(newDate, tody, df).intValue();
				request.setAttribute("nwdate", nwdate);
				request.setAttribute("todaydate", todaydate);
			} else {
				detailDto.setDifferTime(-1);//用来标识是否是 计划结束后的计划
			}
			if(null != detailDto.getId()){
				List<AnnexDto> annexList = factoryService.getProgressAnnexList(detailDto.getId());
				request.setAttribute("annex", annexList);
			}
			request.setAttribute("progress", detailDto);
		}else{
			ProgressDto progressDto = factoryService.queryModelProcessByPlanId(id, false);
			request.setAttribute("progress", progressDto);
		}
		List<TargetDto> list = factoryService.getAllProcessName(id);
		request.setAttribute("prName", list);
		return "progress/addProgress";
	}

	/**
	 * 保存图片
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value="/saveProgressAnnex")
    public Object filesUpload(@RequestParam(value="file",required=false)MultipartFile[] file,
            HttpServletRequest request) throws IOException{
        File targetFile=null;
        String msg="";//返回存储路径
        List<Object> imgList = new ArrayList<Object>();
        Map<String,Object> map = new HashMap<String,Object>();
        Properties pro = new Properties();
        InputStream in = FactoryPlanController.class.getClassLoader().getResourceAsStream("config-development.properties");
        pro.load(in);
        String picPath = pro.getProperty("pic.path");
        String realPath = pro.getProperty("pic.host");
        String ffmpeg = pro.getProperty("pic.ffmpeg");
        if (file!=null && file.length>0) {
            for (int i = 0; i < file.length; i++) {
                String fileName=file[i].getOriginalFilename();//获取文件名加后缀
                if(fileName!=null&&fileName!=""){
                    String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();//存储路径
                    //String path = request.getSession().getServletContext().getRealPath(""); //文件存储位置
                    String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
                    fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
                    String fileAdd = DateUtil.getDateString(new Date(), "yyyyMMdd");
                    String inputPath = "";
                    String outputPath = "";
                    String ffmpegPath = "";
                    //windows下
                    String line=File.separator;
                    String path = "";
                    String returnPath = "";
                    if("\\".equals(line)){
                    	path = request.getSession().getServletContext().getRealPath(""); //文件存储位置
                    	returnPath = returnUrl;
                        inputPath = path+"\\annex\\"+fileAdd+"\\"+fileName;
                        outputPath = path+"\\annex\\"+fileAdd+"\\";
                        ffmpegPath = path+"\\ffmpeg\\ffmpeg.exe";
                    }
                   //linux下

                    if("/".equals(line)){
                        path = picPath;
                        returnPath = realPath;
                         inputPath = path+"/annex/"+fileAdd+"/"+fileName;
                         outputPath = path+"/annex/"+fileAdd+"/";
                         ffmpegPath = ffmpeg;
                    }
                    //先判断文件是否存在
                    File file1 =new File(path+"/annex/"+fileAdd);
                    //如果文件夹不存在则创建    
                    if(!file1 .exists()  && !file1 .isDirectory()){
                        file1 .mkdir();
                    }
                    targetFile = new File(file1,fileName);
                    try {
                        file[i].transferTo(targetFile);
                        String video= ".mp4.MP4.rmvb.RMVB .mov .MOV";
                        if(video.contains(fileF)){
                        	String fName = FileUtil.getFileNameNoEx(fileName);
                        	 msg=returnPath+"/annex/"+fileAdd+"/new_"+fName+".mp4";
                        	 //msg=returnPath+"/annex/"+fileAdd+"/"+fileName;
                        	//视频转码
                             ConvertVideoUtil.getPath(inputPath,outputPath,ffmpegPath,fName);
                        }else{
                        	msg=returnPath+"/annex/"+fileAdd+"/"+fileName;
                        }
                        imgList.add(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        ObjectMapper mapper = new ObjectMapper();
        String content = "";
		try {
			 map.put("path", imgList);
			content = mapper.writeValueAsString(map);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return content;
    }

	/**
	 * 保存进度明细
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/saveProgressDetail")
    public Object saveProgressDetail(@RequestParam Map<String,Object> param,HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		String jsonData1 = param.get("pcoData")==null?"":param.get("pcoData").toString();
		List<ProgressDto> progressDto = JSONArray.parseArray(jsonData1, ProgressDto.class);
		String jsonData3 = param.get("pcoData")==null?"":param.get("pcoData").toString();
		List<ProgressDetailDto> progressDetailDto = JSONArray.parseArray(jsonData3, ProgressDetailDto.class);
		String jsonData2 = param.get("picData")==null?"":param.get("picData").toString();
		List<AnnexDto> annexList = JSONArray.parseArray(jsonData2, AnnexDto.class);
		//存放modelID 为了满足计划过期的情况
		ModelDto modelDto = factoryService.getModel(progressDto.get(0).getModelCode());
		if (modelDto != null && modelDto.getId() != null) {
			progressDto.get(0).setModelId(modelDto.getId());
		}
		Map<String,String> map = new HashMap<String,String>();
		if(StringUtils.isNotEmpty(progressDto.get(0).getCurrentPro())){
			map.put("modelPlanId", progressDto.get(0).getModelPlanId().toString());
			map.put("processName", progressDto.get(0).getCurrentPro());
			Integer modelProcessId = indexAuditService.queryProcessIdByPlanIdAndPlanName(map);
			progressDetailDto.get(0).setModelProcessId(modelProcessId);
		}
        if(null != progressDto && progressDto.size()>0){
        	progressDto.get(0).setStatus("0");
        	progressDto.get(0).setInsertedBy(userId);
        	progressDto.get(0).setInsertedAt(new Date());
        	progressDto.get(0).setUpdatedBy(userId);
        	progressDto.get(0).setUpdatedAt(new Date());

        	progressDetailDto.get(0).setInsertedBy(userId);
        	progressDetailDto.get(0).setInsertedAt(new Date());
        	progressDetailDto.get(0).setUpdatedBy(userId);
        	progressDetailDto.get(0).setUpdatedAt(new Date());

        	factoryService.saveProgressRecord(progressDto.get(0),progressDetailDto.get(0),annexList,userId);
        }
        return returnSuccess("操作成功","");
    }

	/**
	 * 我的进度报告
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/myProgressReport")
	public String myProgressReport(@RequestParam Map<String,Object> map, HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		if("-2".equals(map.get("status"))){
			map.put("submitFlag", "0");
			map.put("status", "");
		}
		List<ProgressDto> list = factoryService.myProgressReportList(map, request, userId);
		if("0".equals(map.get("submitFlag"))){
			map.put("status", "-2");
		}
		List<TargetDto> mTypeList = busModelService.queryAllmodelType();
		request.setAttribute("mTypeList",mTypeList);
		request.setAttribute("list", list);
		request.getSession().setAttribute("myProgressReport", map);
		return "progress/myProgressReport";
	}

	/**
	 * 跳转修改进度页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toEditProgress")
    public Object toEditProgress(@RequestParam Map<String,String> param,HttpServletRequest request){
		Integer id = Integer.parseInt(param.get("mapId"));
		request.setAttribute("map", param);
		ProgressDetailDto detailDto = factoryService.getProgressDetailById(id, false, false, false);

		ModelPlan modelPlan = factoryService.getmodelPlan(detailDto.getModelPlanId());//获取结束时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String endDate = sdf.format(modelPlan.getPlanEndTime());
		String newDate = sdf.format(new Date());
		//判断当前时间是否大于计划结束时间
		//如果大于，则沿用计划结束最后天来提交进度
		detailDto.setDifferTime(-1);//用来标识是否是 计划结束后的计划
		if (DateUtil.middate(newDate, endDate, sdf) > 0) {
			detailDto = factoryService.getProgressDetailById(id, false, true, true);
			//计划时间结束 计算计划总耗时
            detailDto.setDifferTime(DateUtil.middate(newDate, sdf.format(modelPlan.getPlanEndTime()), sdf).intValue());
            detailDto.setPlanTotalTime(1);
		}
		 Map<String,String> maps = new HashMap<String,String>();
         maps.put("currentPro", detailDto.getCurrentPro());
         maps.put("modelPlanId", detailDto.getModelPlanId().toString());
         maps.put("planProgressName", detailDto.getPlanProgress());
         ProgressDto dto = factoryService.getPlanStartTimeByProcessName(maps);
         detailDto.setAccTotalTime(dto.getPlanTotalTime());
         detailDto.setDays(dto.getDay());
		if(null != detailDto.getId()){
			List<AnnexDto> annexList = factoryService.getProgressAnnexList(detailDto.getId());
			request.setAttribute("annex", annexList);
		}
		request.setAttribute("progress", detailDto);
		List<TargetDto> list = factoryService.getAllProcessName(detailDto.getModelPlanId());
		request.setAttribute("prName", list);
        return "progress/editProgress";
    }

	/**
	 * 修改进度详细
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editProgressDetail")
    public Object editProgressDetail(@RequestParam Map<String,Object> param,HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		String jsonData1 = param.get("pcoData")==null?"":param.get("pcoData").toString();
		List<ProgressDto> progressDto = JSONArray.parseArray(jsonData1, ProgressDto.class);
		String jsonData3 = param.get("pcoData")==null?"":param.get("pcoData").toString();
		List<ProgressDetailDto> progressDetailDto = JSONArray.parseArray(jsonData3, ProgressDetailDto.class);
		String jsonData2 = param.get("picData")==null?"":param.get("picData").toString();
		List<AnnexDto> annexList = JSONArray.parseArray(jsonData2, AnnexDto.class);
        if(null != progressDetailDto && progressDetailDto.size()>0){
        	progressDetailDto.get(0).setUpdatedBy(userId);
        	factoryService.saveProgressRecord(progressDto.get(0), progressDetailDto.get(0), annexList, userId);
        }
        return returnSuccess("操作成功","");
    }


	/**
	 * 删除附件
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deleteAnnex")
    public Object delete(Integer id,HttpServletRequest request){
        factoryService.deleteAnnexByid(id);
        return returnSuccess("操作成功","");
    }

	/**
	 * 厂商接受
	 * @param request
	 * @return
	 */
	@RequestMapping("/accept")
	@ResponseBody
    public Object accept(@RequestParam String id,HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id", id);
		map.put("status", "1");
		//先判断是否是第一次接收
		ModelPlan modelPlan = factoryService.getmodelPlan(Integer.valueOf(id));//获取结束时间
		String flag = modelPlan.getReceiveFlag();
		if ("0".equals(flag)) {
			map.put("accDate", new Date());
	    }
		factoryService.accept(map);
        return returnSuccess("操作成功","");
    }
	/**
	 * 我的材料使用列表
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/meterUseList")
	public String meterUseList(@RequestParam Map<String,Object> map, HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		//总条数
		map.put("userId", userId);
		map.put("receiveFlag", "1");
		map.put("count", factoryService.queryPageBusModelPlanCount(map));
		List<ModelDto> list = factoryService.queryPageBusModelPlanList(PageUtils.Page(request,map));
		request.setAttribute("list", list);
		PageUtils.calculate(map);
		return "progress/myPlan";
	}

	/**
	 * 保存材料使用信息
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/saveMeterUsed")
    public Object saveMeterUsed(@RequestParam Map<String,Object> param,HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		String jsonData1 = param.get("pcoData")==null?"":param.get("pcoData").toString();
		List<MeterUsedDto> meterUsedDto = JSONArray.parseArray(jsonData1, MeterUsedDto.class);
        if(null != meterUsedDto && meterUsedDto.size()>0){
        	meterUsedDto.get(0).setUpdatedBy(userId);
        	meterUsedDto.get(0).setInsertedAt(new Date());
        	meterUsedDto.get(0).setInsertedBy(userId);
        	meterUsedDto.get(0).setUpdatedAt(new Date());
        	factoryService.saveMeterUsedRecord(meterUsedDto.get(0));
        }
        return returnSuccess("操作成功","");
    }

	/**
	 * 跳转到v材料使用详细
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toMeterUseView")
	public String toMeterUseView(@RequestParam Map<String,Object> map,HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		map.put("userId", userId);
		map.put("modelCode", map.get("modelCode"));
		List<MeterUsedDto> list = factoryService.queryMeterUsedDetails(map,request);
		for (MeterUsedDto dto : list) {
			if (map.get("avaliablAmount") != null) {
				dto.setAvaliablAmount(map.get("avaliablAmount").toString());
			}
		}
		request.setAttribute("list", list);
		request.setAttribute("modelCode", map.get("modelCode"));
		return "progress/meterUseView";
	}

	@RequestMapping(value = "/editReport")
	public @ResponseBody
	Map<String, Object> editReport(ModelDto modelDto) throws Exception {
		Map<String, Object> mapReport = new HashMap<String, Object>();
		if (modelDto.getReportFreq() <= 0) {
			mapReport.put("infoss", 1);
		}else{
			factoryService.saveReportFreq(modelDto);
		}
		return mapReport;
	}
	@RequestMapping(value = "/checkProcessStatus")
	public @ResponseBody
	Object checkProcessStatus(@RequestParam Map<String,String> map) throws Exception {
		ProgressDto dto=null;
		if(map.size()>0){
			dto = factoryService.getPlanStartTimeByProcessName(map);
		}
		//判断是否是计划结束时间 计算延期天数
		if (!"-1".equals(map.get("differTime"))) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
			String newDate = df.format(new Date());
			//计算延期天数
			List<ModelProcessPlan> processList = factoryPlanDao.queryModelProcessByPlanId(Integer.valueOf(map.get("modelPlanId")));
			Date update = new Date();//取上一个时间
			Date todydate = new Date();//当前结束时间
			for (ModelProcessPlan plan : processList) {
				todydate = plan.getPlanEndTime();//得到当前结束时间
				if (map.get("currentPro").equals(plan.getProcessName())) {
					break;//如果相等,结束,取上一个时间
				}
				update = plan.getPlanEndTime();
			}
			//上一个进度结束时间

			//延期天数=(当前进度结束时间-上一个进度结束时间)*(1-实际完成比例)+当天-当前进度结束时间
			String tody = df.format(todydate);
			String updt = df.format(update);
			//当前进度结束时间-上一个进度结束时间
			int nwdate = DateUtil.middate(tody, updt, df).intValue();
			//当天-当前进度结束时间
			int todaydate = DateUtil.middate(newDate, tody, df).intValue();
			dto.setNwdate(nwdate);
			dto.setTodaydate(todaydate);
		}

		return returnSuccess("操作成功",dto);
	}

	/**
	 * 跳转到v材料修改页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toMeterUseEdit")
	public String toMeterUseEdit(@RequestParam Map<String,Object> map,HttpServletRequest request){
		if(null != map.get("id")){
			MeterUsedDto dto = factoryService.getMeterUsedRecord(Integer.valueOf(map.get("id").toString()));
			if (map.get("avaliablAmount") != null) {
				dto.setAvaliablAmount(map.get("avaliablAmount").toString());
			}
			request.setAttribute("dto", dto);
		}
		return "progress/meterUseEdit";
	}

	/**
	 * 修改材料使用记录
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/usedMeterEdit")
	public Object usedMeterEdit(@RequestParam Map<String,String> param,HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		String jsonData1 = param.get("pcoData")==null?"":param.get("pcoData").toString();
		List<MeterUsedDto> meterUsedDto = JSONArray.parseArray(jsonData1, MeterUsedDto.class);
        if(null != meterUsedDto && meterUsedDto.size()>0){
        	meterUsedDto.get(0).setUpdatedBy(userId);
        	meterUsedDto.get(0).setInsertedAt(new Date());
        	factoryService.usedMeterEdit(meterUsedDto.get(0));
        }
        return returnSuccess("操作成功","");
	}

	/**
	 * 跳转到v材料修改页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toEditPassword")
	public String toEditPassword(HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		request.setAttribute("userId", userId);
		return "progress/toEditPassword";
	}
	/**
	 * 修改用户密码
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updatePassword")
	@ResponseBody
	public Object editPassword(@RequestParam Map<String,String> map, HttpServletRequest request){
		if(map.size()> 0){
			String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
			map.put("id", userId);
			map.put("password",SHAUtil.SHA256(map.get("password")));
			factoryService.factoryUpdatePassword(map);
		}
		return returnSuccess("修改成功", "");
	}
}
